<?php

namespace App\Http\Controllers;

use App\User;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use GuzzleHttp\Client;
use Mews\Captcha\Facades\Captcha;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    public function login(Request $request){
        $credentials = $request->only('username','password','captcha','captchaKey');
        //判断用户是否存在
        $user = User::where('username',$credentials['username'])->first();
        if(!$user){
            return $this->returnJson(1,'管理员账户不存在');
        }
        $client = new Client();
        $url = request()->root() . '/oauth/token';
        $params = array_merge(config('passport.proxy'), [
            'username' => $credentials['username'],
            'password' => $credentials['password'],
        ]);
        try {
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (RequestException $exception) {
            return $this->returnJson(1,'密码输入错误');
        }
    }


    public function logout(){
        if (auth()->guard('api')->check()) {
            auth()->guard('api')->user()->token()->delete();
            return $this->returnJson(0,'登出成功,页面即将跳转...');
        }
    }


    public function captcha(){
        $captcha = Captcha::create('default', true);
        return $this->returnJson(0,'',$captcha);
    }






}